package com.hobee.basic.config.scheduling;

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

/**
 * @author junjie.li
 * @date 2020/9/20 9:37
 */
@Component
public class DynamicSchedule implements SchedulingConfigurer {

    private volatile ScheduledTaskRegistrar registrar;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        this.registrar = scheduledTaskRegistrar;
    }

    public void dynamicAdd(Runnable runnable, String cron) {
        CronTask task = new CronTask(runnable, cron);
        TaskScheduler scheduler = registrar.getScheduler();
        if (scheduler == null) {
            scheduler = new ConcurrentTaskScheduler();
        }
        scheduler.schedule(task.getRunnable(), task.getTrigger());
    }
}
